package com.promise.jokerdream.work.mercenary

import com.promise.jokerdream.database.entity.FormationGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.model.formation.FormationSelection
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 佣兵助阵工作
class MercenaryFormationWork(
    private val config: FormationGameConfigEntity,
    override val uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "佣兵助阵"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询活跃度信息
            val livenessResult = gameApi.queryLiveness()

            livenessResult.foldWithApiException(
                onSuccess = { response ->
                    // 判断upFormations是否小于3
                    if (response.upFormations < 3) {
                        val remainingTimes = 3 - response.upFormations
                        // 使用配置中的助阵类型进行提升
                        upgradeFormation(remainingTimes)
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 提升助阵属性
     */
    private suspend fun upgradeFormation(times: Int): WorkResult {
        return try {
            // 从 JSON 解析助阵选择信息
            val selection = if (config.selectionJson.isEmpty()) {
                FormationSelection.EMPTY
            } else {
                try {
                    val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true; encodeDefaults = true }
                    json.decodeFromString<FormationSelection>(config.selectionJson)
                } catch (e: Exception) {
                    FormationSelection.EMPTY
                }
            }
            
            // 检查配置是否有效
            if (selection.isEmpty) {
                historyManager.addHistory(name, "未配置助阵信息")
                return WorkResult.Success
            }

            val formationType = selection.selectedTypeId
            val formationId = selection.selectedFormationId
            val attrIndex = selection.selectedAttrIndex

            // 循环 times 次，每次传递 times=1
            for (i in 1..times) {
                val upgradeResult = gameApi.upgradeFormationAttr(
                    formationType = formationType,
                    formationId = formationId,
                    attrIndex = attrIndex,
                    times = 1
                )

                upgradeResult.foldWithApiException(
                    onSuccess = { response ->
                        historyManager.addHistory(name, response.getDescription())
                    },
                    onFailure = { code, msg ->
                        historyManager.addHistory(name, msg, code)
                    }
                )
            }

            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}